<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Intervention\Image\Facades\Image;
use App\Listeners\QueryListener;
use App\Http\Model\User;
use App\Http\Model\Orders;
use App\Http\Model\OrdersInfo;
use Config;
class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    //Oauth2.0获取微信用户信息函数
    public function getUserInfo($code){
	    $appid = Config::get('wechat.app_id');
	    $appsecret = Config::get('wechat.secret');

	    //oauth2的方式获得openid
	    $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
	    $access_token_json = $this->https_request($access_token_url);
	    $access_token_array = json_decode($access_token_json, true);
	    $openid = $access_token_array['openid'];


	    //非oauth2的方式获得全局access token
	    $new_access_token = $this->getAccessToken();

	    //全局access token获得用户基本信息
	    $userinfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$new_access_token&openid=$openid";
	    $userinfo_json = $this->https_request($userinfo_url);
	    $userinfo_array = json_decode($userinfo_json, true);
	    return $userinfo_array;
  	}
  	//采用curl方式获取返回数据
  	public function https_request($url){
	    $curl = curl_init();
	    curl_setopt($curl, CURLOPT_URL, $url);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	    $data = curl_exec($curl);
	    if (curl_errno($curl)) {return 'ERROR '.curl_error($curl);}
	    curl_close($curl);
	    return $data;
   }
   function httpRequest($url, $data = null){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        if(!empty($data)){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        // dd($data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $opt = curl_exec($ch);
        curl_close($ch);
        return $opt;
    }
   //获取Accesstoken
   public function getAccessToken(){
   			$appid = Config::get('wechat.app_id');
		    $appsecret = Config::get('wechat.secret');
	   		$new_access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
		    $new_access_token_json = $this->https_request($new_access_token_url);
		    $new_access_token_array = json_decode($new_access_token_json, true);
		    $new_access_token = $new_access_token_array['access_token'];

		    session(['access_token'=>$new_access_token]);
		    session(['access_token_time'=>time()]);
		    session()->save();
		    return $new_access_token;
   }
   //生成二维码，获取tickt
    public function gettickt(){
        $accessToken = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$accessToken;
        $uid = session('uid');
        $post = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": $uid}}";

        $res = $this->httpRequest($url, $post);
        $data = json_decode($res,true);
        // dd(date("Y-m-d H:i:s",session("access_token_time")));
        return $data['ticket'];
    }
    public function ewm(){
        $user = new User;
        $tickets = UrlEncode($this->gettickt());
        $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$tickets;
        $img = file_get_contents($url);
        $userInfo = $user->find(session('uid'));
        $imgname = $userInfo->open_id;
        $face = $userInfo->face;
        $username = $userInfo->username;

        $path_1 = Config::get('app.domain_name').'upload/background.jpg';
        $size_1 = getimagesize($path_1);
        $size = $size_1[0]*116/475;
        file_put_contents('upload/user/'.session('uid').'.jpg',$img);
        Image::make($img)->resize($size, $size)->save('upload/user/'.$imgname.'.jpg');
        $path_2 = Config::get('app.domain_name').'upload/user/'.$imgname.'.jpg';
        // 创建图片对象
        $image_1 = imagecreatefromjpeg($path_1);
        $image_2 = imagecreatefromjpeg($path_2);
        $size_2 = getimagesize($path_2);
        $x = $size_1[0]*179/475;
        $y = $size_1[1]*720/1381;
        // 合成图片
        imagecopymerge($image_1, $image_2, $x, $y, 0, 0, imagesx($image_2), imagesy($image_2), 100);
        Imagejpeg($image_1, 'upload/user/'.$imgname.'.jpg');

        $dst_path = 'upload/user/'.$imgname.'.jpg';
        //创建图片的实例
        $dst = imagecreatefromstring(file_get_contents($dst_path));
        //打上文字
        $font = 'simsun/simsun.ttc';//字体路径

        $black = imagecolorallocate($dst, 255,204,0);//字体颜色
        imagefttext($dst, 26, 0, 400, 275, $black, $font, $username);
        imagefttext($dst, 26, 0, 401, 275, $black, $font, $username);
        imagefttext($dst, 26, 0, 402, 275, $black, $font, $username);
        imagefttext($dst, 26, 0, 403, 275, $black, $font, $username);

        //输出图片
        list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);
        Imagejpeg($dst, 'upload/user/'.$imgname.'.jpg');


        // $dst = imagecreatefromstring($image_1);
        // //打上文字
        // $font = '/homes/simsun/simsun.ttc';//字体路径

        // $black = imagecolorallocate($dst, 0x00, 0x00, 0x00);//字体颜色
        // imagefttext($dst, 13, 0, 20, 20, $black, $font, '天路本草');
        // //输出图片
        // list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);


        // $path_4 = Config::get('app.domain_name').'upload/user/'.$imgname.'.jpg';
        // $image_4 = imagecreatefromjpeg($path_4);
        // $face_url = file_get_contents($face);
        // file_put_contents('upload/user-face/'.$imgname.'.png',$face_url);
        // $path_3 = Config::get('app.domain_name').'upload/user-face/'.$imgname.'.png';
        // $image_3 = imagecreatefrompng($path_3);
        // $size_3 = getimagesize($path_3);
        // $size_4 = getimagesize($path_4);
        // $x2 = $size_4[0]*113/275;
        // $y2 = $size_4[1]/160;
        // imagecopymerge($image_4, $image_3, $x2, $y2, 0, 0, imagesx($image_3), imagesy($image_3), 100);
        // // 输出合成图片
        // Imagejpeg($image_4, 'upload/user/'.$imgname.'.jpg');
        return true;
    }
    //模板消息
    //分销商申请成功推送模板消息
    public function fenxiao_template($openid){
        $app = app('wechat');
        $user = new User;
        $notice = $app->notice;
        $template_id = '-3cCEZWHHGMot9R5jMD9PqPnhAR_CC0Xr_wYXnuYIW8';
        $userInfo = $user->where('open_id',$openid)->first();
        $url = 'https://s.wcd.im/v/2e5u1Z3a/';
        $data = array(
            "first"=>'尊敬的'.$userInfo->username.'，您的申请已通过，恭喜您成为天路本草品牌合伙人',
            "keyword1"=>'天路本草品牌合伙人申请',
            "keyword2"=>'申请成功',
            "keyword3"=>date("Y-m-d H:i:s"),
            "remark"=>'点击了解品牌合伙人须知',
        );
        $res = $notice->uses($template_id)->withUrl($url)->andData($data)->andReceiver($openid)->send();
        return $res;
    }
    //驳回
    public function fenxiao_fail_template($openid,$message){
        $app = app('wechat');
        $user = new User;
        $notice = $app->notice;
        $template_id = '8vPeDRjDvs9DY4LpKgbBuoou7LZn1di_NOOE0NwRQsE';
        $userInfo = $user->where('open_id',$openid)->first();
        $url = Config::get('app.domain_name');
        $data = array(
            "first"=>'尊敬的'.$userInfo->username.'您的申请被驳回',
            "keyword1"=>$message,
            "keyword2"=>'认证失败',
            "remark"=>'详情',
        );
        $res = $notice->uses($template_id)->withUrl($url)->andData($data)->andReceiver($openid)->send();
        return $res;
    }
    //取消分销商
    public function quxiao_template($openid,$message){
        $app = app('wechat');
        $user = new User;
        $notice = $app->notice;
        $template_id = '8vPeDRjDvs9DY4LpKgbBuoou7LZn1di_NOOE0NwRQsE';
        $userInfo = $user->where('open_id',$openid)->first();
        $url = Config::get('app.domain_name');
        $data = array(
            "first"=>'尊敬的'.$userInfo->username.'您的分销商身份被取消',
            "keyword1"=>$message,
            "keyword2"=>'身份取消',
            "remark"=>'详情',
        );
        $res = $notice->uses($template_id)->withUrl($url)->andData($data)->andReceiver($openid)->send();
        return $res;
    }
    //商品发货提醒
    public function goods_template($userInfo,$logistic_code,$id){
        $app = app('wechat');
        $notice = $app->notice;
        $template_id = '0CyKnimxvDj84vDgkO9NmedmTG01qcb0jr3XB_r14xA';
        $url = Config::get('app.domain_name').'logistic/'.$id;
        $company_name = Config::get('app.company_name');
        $data = array(
            "first"=>'亲，宝贝已经启程了，好想快点来到你身边',
            "delivername"=>$company_name,
            "ordername"=>$logistic_code,
            "remark"=>'点击了解物流信息',
        );
        $res = $notice->uses($template_id)->withUrl($url)->andData($data)->andReceiver($userInfo->open_id)->send();
        return $res;
    }
    //客服模板消息提醒
    public function serviceTemplate(){
        $app = app('wechat');
        $user = new User;
        $notice = $app->notice;
        $template_id = 'Di_kMnpAeqW8aoqv9_3OHd6WpMSZ0aAG2t57yT5MQkk';
        $url = Config::get('app.domain_name');
        $userInfo = $user->select('open_id')->where('user_type','1')->get();
        $data = array(
            "first"=>'你好，您有新的客服消息等待回复,请及时登录客服平台回复！',
            "keyword1"=>'商家咨询',
            "keyword2"=>'请登录客服平台查看',
            "remark"=>'请及时登录客服平台回复！',
        );
        foreach ($userInfo as $key => $value) {
          $res = $notice->uses($template_id)->withUrl($url)->andData($data)->andReceiver($value->open_id)->send();
        }
        // return $res;
    }
    //返现提醒
    public function rebackTemplate($userInfo,$money){
        $app = app('wechat');
        $user = new User;
        $notice = $app->notice;
        $template_id = 'SO4N6WzNeOV_tsdT3lgvO0XSElW9e1IA80QDWnrJP9A';
        $url = Config::get('app.domain_name');
        $data = array(
            "first"=>'尊敬的'.$userInfo->username.',恭喜您获得返现，请及时进入个人中心查收！',
            "keyword1"=>'上月旗下会员消费返现',
            "keyword2"=>$money,
            "keyword2"=>'系统自动返现',
            "remark"=>'请及时查收！',
        );
          $res = $notice->uses($template_id)->withUrl($url)->andData($data)->andReceiver($value->open_id)->send();
        return $res;
    }

    //发送模板消息提醒管理员有新用户提现
    public function withdrawalsTemplate($user_id){
        $app = app('wechat');
        $user = new User;
        $withdrawals = new Withdrawals;
        $notice = $app->notice;
        $template_id = 'G-5EgbrPDzP6PMb-0I0SBWIChpxxsbHVJqHxwmBCSc0';
        $url = Config::get('app.domain_name');
        $kefuInfo = $user->where('user_type','1')->get();
        $withdrawalsInfo = $withdrawals->select('user.username','withdrawals.money')->leftJoin('user','user.id','=','withdrawals.user_id')->where('status','0')->first();
        $data = array(
            "first"=>'有新的用户发起提现请求，请及时处理！',
            "keyword1"=>$withdrawalsInfo->username,
            "keyword2"=>$withdrawalsInfo->data('Y-m-d'),
            "keyword3"=>$withdrawalsInfo->money,
            "keyword3"=>'微信提现！',
            "remark"=>'请及时处理请求！',
        );
        foreach ($kefuInfo as $key => $value) {
          $res = $notice->uses($template_id)->withUrl($url)->andData($data)->andReceiver($value->open_id)->send();
        }
        return $res;
    }
    //计算用户本月销售额
    public function saleVolume($uid,$identity){
        $orders = new Orders;
        $ordersInfo = new OrdersInfo;
        $users = new User;
        if($identity==0){
            $sumPrice='';
            $userOrdersInfo = $orders->select('orders.*')->leftJoin('user','user.id','=','user_id')->where('user.pid',$uid)->where("orders.status", ">", "3")->get();
            $sumPrice = $this->sum($userOrdersInfo);
            return $sumPrice;
        }else if($identity==1){
            $sumPrice=array();
            $userOrdersInfo = $orders->select('orders.*')->leftJoin('user','user.id','=','user_id')->where('user.pid',$uid)->where('user.identity',0)->where("orders.status", ">", "3")->get();
            $sumPrice['member'] = $this->sum($userOrdersInfo);
            $businessOrdersInfo = $orders->select('orders.*')->leftJoin('user','user.id','=','user_id')->where('user.pid',$uid)->where('user.identity',1)->where("orders.status", ">", "3")->get();
            $sumPrice['business'] = $this->sum($businessOrdersInfo);
            if(empty($sumPrice['member']) && empty($sumPrice['business'])) return false;
            return $sumPrice;
        }
    }
    //计算订单总价
    public function sum($ordersData){
        $ordersInfo = new ordersInfo;
        $sumPrice='';
        foreach ($ordersData as $key => $value) {
            $ordersDetail = $ordersInfo->where('orders_id',$value->id)->get();
            foreach ($ordersDetail as $k => $v) {
                $sumPrice += $v->price*$v->num;
            }
        }
        return $sumPrice;
    }
}
